package com.bunde.sax;

import com.bunde.model.User;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.List;


public class XmlParseHandler extends DefaultHandler {
    List<User> users;
    private User cur;
    private String preEle;

    public XmlParseHandler(){
        users = new ArrayList<>();
    }

    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        System.out.println("startDocument ：XmlParseHandler start parse docment");
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        System.out.println("startElement: " + uri + ", " + localName + ", " + qName + ", " + attributes);

        if(qName.equals("user")){
            cur = new User();
        }else {
            preEle = qName;
        }

    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        System.out.println("characters : " + start + ", " + length + ", " + new String(ch, start, length));
        if(preEle.equals("name")){
            cur.setName(new String(ch, start, length));
        }else if(preEle.equals("age")){
            cur.setAge(Integer.valueOf(new String(ch, start, length)));
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        System.out.println("endElement : " + uri + ", " + localName + ", " + qName);
        if (qName.equals("user")){
            users.add(cur);
            cur = null;
        }
        // 注意：endElement之后也会走一次characters
        preEle = "";
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        System.out.println("endDocument: ");
    }

    public List<User> getUsers(){
        return users;
    }
}
